import { Component } from 'react';
import { View } from '@tarojs/components';
import { AtSwitch, AtButton } from 'taro-ui';
import Taro from '@tarojs/taro';
import InputItem from '@/components/InputItem';
import { saveReceiver } from '@/service/apis/order';
import './index.scss';

export default class Index extends Component {
  state = {
    name: '',
    phone: '',
    isDefault: false,
  };
  componentDidMount = async () => {};

  onNameChange = (value?: string) => {
    console.log(value);
    this.setState({
      name: value,
    });
  };

  onPhoneChange = (value?: string) => {
    console.log(value);
    this.setState({
      phone: value,
    });
  };

  onDefaultChange = (value: boolean) => {
    this.setState({
      isDefault: value,
    });
  };

  saveReceiver = async () => {
    const { phone, name, isDefault } = this.state;
    if (!name) {
      return Taro.showToast({
        title: '请输入联系人姓名',
        icon: 'none',
      });
    }
    if (!phone) {
      return Taro.showToast({
        title: '请输入联系人手机号',
        icon: 'none',
      });
    }
    try {
      const res = await saveReceiver({
        name,
        phone,
        isDefault,
      });
      console.log(res);
      Taro.showToast({
        title: '保存成功',
        duration: 2000,
      });
      setTimeout(() => {
        Taro.navigateBack();
      }, 2000);
    } catch (err) {
      console.log(err);
      Taro.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000,
      });
    }
  };

  render() {
    const { name, phone, isDefault } = this.state;
    return (
      <View className="receiver-container">
        <View className="section-block">
          <InputItem
            name="name"
            title="姓名"
            placeholder="请填写联系人姓名"
            value={name}
            required
            bordered
            onChange={this.onNameChange}
          />
          <InputItem
            required
            name="phone"
            title="手机号码"
            placeholder="请填写联系人手机号"
            value={phone}
            onChange={this.onPhoneChange}
          />
        </View>
        <View className="section-block">
          <AtSwitch title="设为默认联系人" checked={isDefault} onChange={this.onDefaultChange} />
        </View>
        <View className="bottom-btn">
          <AtButton type="primary" onClick={this.saveReceiver}>
            保存
          </AtButton>
        </View>
      </View>
    );
  }
}
